#include "xaudioplay.h"
#include <QAudioOutput>
#include <QMutex>

class CXAudioPlay : public XAudioPlay
{
public:
    virtual bool Start()
    {
        Stop();
        m_mutex.lock();
        QAudioFormat fmt;
        fmt.setSampleRate(m_iSampleRate);
        fmt.setSampleSize(16);
        fmt.setChannelCount(m_iChannel);
        fmt.setCodec("audio/pcm");
        fmt.setByteOrder(QAudioFormat::LittleEndian);
        fmt.setSampleType(QAudioFormat::UnSignedInt);
        m_output = new QAudioOutput(fmt);
        m_io = m_output->start();
        m_mutex.unlock();
    }

    bool Stop()
    {
        m_mutex.lock();
        if(m_output)
        {
            m_output->stop();
            delete m_output;
            m_output = NULL;
            m_io = NULL;
        }
        m_mutex.unlock();
    }

    virtual bool Play(bool isplay)
    {
        m_mutex.lock();
        if(!m_output)
        {
            m_mutex.unlock();
            return false;
        }

        if(isplay)
        {
            m_output->resume();
        }
        else
        {
            m_output->suspend();
        }
        m_mutex.unlock();
        return true;
    }

    virtual bool Write(const char* data, int datasize)
    {
        if(m_io)
            m_io->write(data, datasize);
        return true;
    }

    virtual int GetFree()
    {
        m_mutex.lock();
       if(!m_output)
       {
           m_mutex.unlock();
           return 0;
       }
       int free = m_output->bytesFree();
       m_mutex.unlock();
       return free;
    }

    CXAudioPlay() : m_output(NULL), m_io(NULL)
    {
    }

protected:
    QAudioOutput *m_output;
    QIODevice *m_io;
    QMutex m_mutex;
};

 XAudioPlay* XAudioPlay::Get()
 {
     static CXAudioPlay ap;
     return &ap;
 }

XAudioPlay::XAudioPlay() : m_iSampleRate(48000), m_iSampleSize(16), m_iChannel(2)
{

}
